package com.gitee.gphomework.mybatis.typehandler.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created on 2020/5/9
 * Title: 经营范围实体转换
 * Description: 经营范围实体转换
 * Copyright: Copyright(c) 2020
 * Company:
 *
 * @author yifeng
 */
public class BusinessScopeTypeHandler extends BaseTypeHandler<List<Integer>> {


    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<Integer> parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, listToString(parameter));
    }

    @Override
    public List<Integer> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return stringToList(rs.getString(columnName));
    }

    @Override
    public List<Integer> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return stringToList(rs.getString(columnIndex));
    }

    @Override
    public List<Integer> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return stringToList(cs.getString(columnIndex));
    }

    private String listToString(List<Integer> l) {
        if (l == null || l.isEmpty()) {
            return "";
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (Integer integer : l) {
            stringBuilder.append(integer).append(",");
        }
        return stringBuilder.toString().substring(0, stringBuilder.length() - 1);
    }

    private List<Integer> stringToList(String s) {
        List<Integer> l = new ArrayList<>();
        if (s == null || s.isEmpty()) {
            return l;
        }
        String[] datas = s.split(",");
        for (String data : datas) {
            l.add(Integer.valueOf(data));
        }
        return l;
    }

}
